package nl.science.uva.pico.operator;

import nl.science.uva.pico.ProgramCounter;
import nl.science.uva.pico.Stack;
import nl.science.uva.pico.operand.Operand;
import nl.uva.science.pico.stacklanguage.types.LabelInstrList;

/** 
 * IfLess compares 2 integer values 
 * 
 * @author Ivo van Dongen, Karel Pieterson
 * @version 1.0  
 */
public class IfLess extends Operator {

	public IfLess(Stack stack, ProgramCounter programCounter,LabelInstrList programListing) {
		super(stack, programCounter, programListing);
	}

    /** 
     * ifl This instruction is similar to ifeq and determines the relative ordering 
     * of two integer constants (or string constants)  x1 < x2
     *   
     *  @throws IllegalStateException
     */	
	@Override
	public void perform() {
		Operand[] operands = new Operand[2];
		
		if(getStack().size() >= 3) {
			operands[0] = getStack().pop();
			operands[1] = getStack().pop();

			Integer label = getStack().pop().getIntegerValue();
			
			boolean equals = false;
			if(operands[0].isStringConstant() && operands[1].isStringConstant()) {
				if(operands[0].getStringValue().compareTo(operands[1].getStringValue()) < 0) {
					equals = true;
				}
			} else if(operands[0].isIntegerConstant() && operands[1].isIntegerConstant()) {
				equals = operands[0].getIntegerValue() < operands[1].getIntegerValue();
			} else {
				throw new IllegalStateException("IfLess can only compare similar types");
			}
			
			if(equals) {
				gotoLabel(label);
			}
		} else {
			throw new IllegalStateException(" Too few operands, IfLess needs 2 operands");
		}
		
	}

}
